/**
 * 固定资产管理系统 - 智能建议组件
 * 基于数据分析提供管理洞察和优化建议
 * 遵循配色规范和模块化架构
 */

class SmartInsights {
    constructor() {
        this.colors = {
            primary: '#1e3a8a',
            secondary: '#64748b', 
            success: '#059669',
            warning: '#d97706',
            danger: '#dc2626',
            info: '#0284c7'
        };
        
        this.insights = [];
        this.recommendations = [];
        this.trends = [];
        
        this.init();
    }

    init() {
        console.log('🧠 初始化智能建议组件...');
        
        this.generateInsights();
        this.createInsightsPanel();
        this.startPeriodicAnalysis();
        
        console.log('✅ 智能建议组件已启动');
    }

    generateInsights() {
        // 生成智能洞察
        this.insights = [
            {
                id: 'utilization_low',
                type: 'warning',
                title: '资产利用率偏低',
                description: 'IT部门有28台设备闲置超过30天，建议重新分配或回收',
                impact: 'medium',
                savings: 450000,
                action: '重新分配闲置资产',
                category: 'efficiency'
            },
            {
                id: 'maintenance_overdue',
                type: 'danger', 
                title: '维护计划滞后',
                description: '12台关键设备超过预定维护周期，存在故障风险',
                impact: 'high',
                cost: 125000,
                action: '立即安排预防性维护',
                category: 'maintenance'
            },
            {
                id: 'procurement_optimization',
                type: 'info',
                title: '采购优化机会',
                description: '统一采购笔记本电脑可节省15%成本，建议集中采购',
                impact: 'medium',
                savings: 230000,
                action: '制定集中采购计划',
                category: 'procurement'
            },
            {
                id: 'depreciation_alert',
                type: 'warning',
                title: '资产折旧分析',
                description: '45台设备将在6个月内完全折旧，建议评估更新计划',
                impact: 'low',
                cost: 890000,
                action: '制定资产更新计划',
                category: 'financial'
            },
            {
                id: 'compliance_check',
                type: 'success',
                title: '合规性良好',
                description: '资产管理符合企业标准，文档完整性达95%',
                impact: 'positive',
                score: 95,
                action: '继续保持标准',
                category: 'compliance'
            }
        ];

        // 生成改进建议
        this.recommendations = [
            {
                title: '实施预测性维护',
                description: '基于设备使用数据，提前预测维护需求',
                priority: 'high',
                roi: 180,
                timeframe: '3个月',
                resources: '需要IoT传感器和分析软件'
            },
            {
                title: '优化资产配置',
                description: '根据使用频率重新分配资产，提高整体利用率',
                priority: 'medium',
                roi: 125,
                timeframe: '1个月',
                resources: '需要详细使用情况分析'
            },
            {
                title: '建立资产生命周期管理',
                description: '制定从采购到报废的全生命周期管理流程',
                priority: 'medium',
                roi: 200,
                timeframe: '6个月',
                resources: '需要流程设计和培训'
            }
        ];
    }

    createInsightsPanel() {
        const container = this.createContainer();
        if (!container) return;

        const panel = document.createElement('div');
        panel.className = 'smart-insights-panel';
        panel.innerHTML = `
            <div class="insights-header">
                <h3>
                    <i class="fas fa-brain"></i>
                    智能分析与建议
                    <span class="insights-count">${this.insights.length}</span>
                </h3>
                <div class="insights-controls">
                    <button class="insight-btn" onclick="smartInsights.refreshAnalysis()" title="刷新分析">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    <button class="insight-btn" onclick="smartInsights.exportReport()" title="导出报告">
                        <i class="fas fa-file-export"></i>
                    </button>
                </div>
            </div>
            
            <div class="insights-tabs">
                <button class="tab-btn active" onclick="smartInsights.switchTab('insights')">
                    <i class="fas fa-lightbulb"></i> 智能洞察
                </button>
                <button class="tab-btn" onclick="smartInsights.switchTab('recommendations')">
                    <i class="fas fa-rocket"></i> 改进建议
                </button>
                <button class="tab-btn" onclick="smartInsights.switchTab('trends')">
                    <i class="fas fa-chart-line"></i> 趋势分析
                </button>
            </div>
            
            <div class="insights-content">
                <div class="tab-content active" data-tab="insights">
                    ${this.renderInsights()}
                </div>
                <div class="tab-content" data-tab="recommendations">
                    ${this.renderRecommendations()}
                </div>
                <div class="tab-content" data-tab="trends">
                    ${this.renderTrends()}
                </div>
            </div>
        `;

        container.appendChild(panel);
    }

    createContainer() {
        const statsGrid = document.querySelector('.stats-grid');
        if (!statsGrid) return null;

        const container = document.createElement('div');
        container.className = 'stats-card smart-insights-container';
        container.style.gridColumn = '1 / -1'; // 占据整个宽度
        statsGrid.appendChild(container);
        
        return container;
    }

    renderInsights() {
        const insightsByCategory = this.groupInsightsByCategory();
        
        return `
            <div class="insights-summary">
                <div class="summary-item high">
                    <span class="summary-count">${this.insights.filter(i => i.impact === 'high').length}</span>
                    <span class="summary-label">高优先级</span>
                </div>
                <div class="summary-item medium">
                    <span class="summary-count">${this.insights.filter(i => i.impact === 'medium').length}</span>
                    <span class="summary-label">中优先级</span>
                </div>
                <div class="summary-item low">
                    <span class="summary-count">${this.insights.filter(i => i.impact === 'low' || i.impact === 'positive').length}</span>
                    <span class="summary-label">低优先级</span>
                </div>
            </div>
            
            <div class="insights-list">
                ${this.insights.map(insight => this.renderInsightCard(insight)).join('')}
            </div>
        `;
    }

    renderInsightCard(insight) {
        const iconMap = {
            efficiency: 'fa-chart-line',
            maintenance: 'fa-tools', 
            procurement: 'fa-shopping-cart',
            financial: 'fa-dollar-sign',
            compliance: 'fa-shield-alt'
        };

        const impactColors = {
            high: this.colors.danger,
            medium: this.colors.warning,
            low: this.colors.info,
            positive: this.colors.success
        };

        return `
            <div class="insight-card ${insight.type}" data-impact="${insight.impact}">
                <div class="insight-header">
                    <div class="insight-icon">
                        <i class="fas ${iconMap[insight.category]}"></i>
                    </div>
                    <div class="insight-title-section">
                        <h4 class="insight-title">${insight.title}</h4>
                        <span class="insight-category">${this.getCategoryName(insight.category)}</span>
                    </div>
                    <div class="insight-impact" style="color: ${impactColors[insight.impact]}">
                        ${this.getImpactLabel(insight.impact)}
                    </div>
                </div>
                
                <div class="insight-body">
                    <p class="insight-description">${insight.description}</p>
                    
                    <div class="insight-metrics">
                        ${insight.savings ? `
                            <div class="metric-item positive">
                                <i class="fas fa-arrow-up"></i>
                                <span>节省: ¥${(insight.savings / 10000).toFixed(1)}万</span>
                            </div>
                        ` : ''}
                        ${insight.cost ? `
                            <div class="metric-item negative">
                                <i class="fas fa-arrow-down"></i>
                                <span>风险成本: ¥${(insight.cost / 10000).toFixed(1)}万</span>
                            </div>
                        ` : ''}
                        ${insight.score ? `
                            <div class="metric-item score">
                                <i class="fas fa-star"></i>
                                <span>评分: ${insight.score}%</span>
                            </div>
                        ` : ''}
                    </div>
                </div>
                
                <div class="insight-actions">
                    <button class="action-btn primary" onclick="smartInsights.takeAction('${insight.id}')">
                        ${insight.action}
                    </button>
                    <button class="action-btn secondary" onclick="smartInsights.viewDetails('${insight.id}')">
                        查看详情
                    </button>
                </div>
            </div>
        `;
    }

    renderRecommendations() {
        return `
            <div class="recommendations-list">
                ${this.recommendations.map(rec => this.renderRecommendationCard(rec)).join('')}
            </div>
        `;
    }

    renderRecommendationCard(rec) {
        const priorityColors = {
            high: this.colors.danger,
            medium: this.colors.warning,
            low: this.colors.info
        };

        return `
            <div class="recommendation-card">
                <div class="rec-header">
                    <h4 class="rec-title">${rec.title}</h4>
                    <span class="rec-priority ${rec.priority}" style="background: ${priorityColors[rec.priority]}">
                        ${rec.priority === 'high' ? '高优先级' : rec.priority === 'medium' ? '中优先级' : '低优先级'}
                    </span>
                </div>
                
                <p class="rec-description">${rec.description}</p>
                
                <div class="rec-metrics">
                    <div class="rec-metric">
                        <span class="metric-label">预期ROI</span>
                        <span class="metric-value">${rec.roi}%</span>
                    </div>
                    <div class="rec-metric">
                        <span class="metric-label">实施周期</span>
                        <span class="metric-value">${rec.timeframe}</span>
                    </div>
                </div>
                
                <div class="rec-resources">
                    <strong>所需资源:</strong> ${rec.resources}
                </div>
                
                <div class="rec-actions">
                    <button class="action-btn primary" onclick="smartInsights.implementRecommendation('${rec.title}')">
                        开始实施
                    </button>
                    <button class="action-btn secondary" onclick="smartInsights.scheduleReview('${rec.title}')">
                        稍后评估
                    </button>
                </div>
            </div>
        `;
    }

    renderTrends() {
        return `
            <div class="trends-container">
                <div class="trend-summary">
                    <h4>📊 关键趋势指标</h4>
                    <div class="trend-metrics">
                        <div class="trend-metric">
                            <span class="trend-value">+15%</span>
                            <span class="trend-label">资产利用率</span>
                            <i class="fas fa-arrow-up trend-arrow positive"></i>
                        </div>
                        <div class="trend-metric">
                            <span class="trend-value">-8%</span>
                            <span class="trend-label">维修成本</span>
                            <i class="fas fa-arrow-down trend-arrow positive"></i>
                        </div>
                        <div class="trend-metric">
                            <span class="trend-value">+22%</span>
                            <span class="trend-label">资产价值</span>
                            <i class="fas fa-arrow-up trend-arrow positive"></i>
                        </div>
                    </div>
                </div>
                
                <div class="trend-charts">
                    <div class="mini-trend-chart">
                        <h5>资产增长趋势</h5>
                        <div class="trend-line" id="asset-growth-trend"></div>
                    </div>
                    <div class="mini-trend-chart">
                        <h5>维修频率变化</h5>
                        <div class="trend-line" id="maintenance-trend"></div>
                    </div>
                </div>
            </div>
        `;
    }

    groupInsightsByCategory() {
        return this.insights.reduce((acc, insight) => {
            if (!acc[insight.category]) {
                acc[insight.category] = [];
            }
            acc[insight.category].push(insight);
            return acc;
        }, {});
    }

    getCategoryName(category) {
        const names = {
            efficiency: '效率优化',
            maintenance: '维护管理',
            procurement: '采购优化',
            financial: '财务分析',
            compliance: '合规检查'
        };
        return names[category] || category;
    }

    getImpactLabel(impact) {
        const labels = {
            high: '高影响',
            medium: '中影响', 
            low: '低影响',
            positive: '积极'
        };
        return labels[impact] || impact;
    }

    switchTab(tabName) {
        // 切换标签页
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        
        document.querySelector(`[onclick="smartInsights.switchTab('${tabName}')"]`).classList.add('active');
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        
        console.log(`📋 切换到标签页: ${tabName}`);
    }

    refreshAnalysis() {
        console.log('🔄 刷新智能分析...');
        
        // 重新生成洞察
        this.generateInsights();
        
        // 更新显示
        const insightsContent = document.querySelector('[data-tab="insights"]');
        if (insightsContent) {
            insightsContent.innerHTML = this.renderInsights();
        }
        
        window.advancedFeatures?.showNotification('分析刷新', '智能分析已更新到最新数据', 'success');
    }

    exportReport() {
        console.log('📄 导出智能分析报告...');
        
        // 模拟导出
        const reportData = {
            timestamp: new Date().toISOString(),
            insights: this.insights,
            recommendations: this.recommendations,
            summary: {
                totalInsights: this.insights.length,
                highPriority: this.insights.filter(i => i.impact === 'high').length,
                potentialSavings: this.insights.reduce((sum, i) => sum + (i.savings || 0), 0)
            }
        };
        
        console.log('📊 报告数据:', reportData);
        window.advancedFeatures?.showNotification('报告导出', '智能分析报告已导出', 'success');
    }

    takeAction(insightId) {
        const insight = this.insights.find(i => i.id === insightId);
        if (insight) {
            console.log(`🎯 执行操作: ${insight.action}`);
            window.advancedFeatures?.showNotification('操作执行', `已开始执行: ${insight.action}`, 'info');
        }
    }

    viewDetails(insightId) {
        const insight = this.insights.find(i => i.id === insightId);
        if (insight) {
            console.log(`👁️ 查看详情: ${insight.title}`);
            window.advancedFeatures?.showNotification('详情查看', `正在加载 ${insight.title} 的详细信息`, 'info');
        }
    }

    implementRecommendation(title) {
        console.log(`🚀 实施建议: ${title}`);
        window.advancedFeatures?.showNotification('建议实施', `已开始实施建议: ${title}`, 'success');
    }

    scheduleReview(title) {
        console.log(`📅 安排评估: ${title}`);
        window.advancedFeatures?.showNotification('评估安排', `已安排评估: ${title}`, 'info');
    }

    startPeriodicAnalysis() {
        // 每小时重新分析一次
        setInterval(() => {
            this.generateInsights();
            console.log('🧠 定期智能分析已完成');
        }, 3600000); // 1小时
    }
}

// 自动初始化
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        window.smartInsights = new SmartInsights();
        console.log('🧠 智能建议组件已启动');
    }, 4000); // 在其他组件之后启动
});